#include <stdio.h>
#include "cmd_handle.h"
#include <string.h>
#include "cmd_cp.h"
#include "cmd_ls.h"

#define DEBUG

int cmd_execute(char *cmd_str)
{
	cmd_t command;
	int ret;

	if (cmd_str == NULL)
	{
		return -1;
	}

	init_command_struct(&command);

	ret = cmd_parse(cmd_str, &command);
	if (ret == -1)
	{
		return -1;
	}

	ret = cmd_dispatch(&command);
	if (ret == -1)
	{
		return -1;
	}

	return 0;
}

// 初始化命令结构体
void init_command_struct(cmd_t *pcmd)
{
	memset(pcmd->cmd_name, 0, SZ_NAME);

	for (int i = 0; i < SZ_COUNT; i++)
	{
		memset(pcmd->cmd_arg_list[i], 0, SZ_ARG);
	}

	pcmd->cmd_arg_count = 0;
}

// 打印命令结构体
void print_command_info(cmd_t *pcmd)
{
	printf("=======================\n");

	printf("[DEBUG] cmd name:< %s >\n", pcmd->cmd_name);
	printf("[DEBUG] cmd arg count:< %d >\n", pcmd->cmd_arg_count);
	printf("[DEBUG] cmd arg list:");

	for (int i = 0; i < pcmd->cmd_arg_count; i++)
	{
		printf("%s\n", pcmd->cmd_arg_list[i]);
	}

	printf("=========================\n");
}

// 命令解析 对命令进行拆分
int cmd_parse(char *cmd_str, cmd_t *pcmd)
{
	char *p_cmd_name = NULL;
	char *p_cmd_arg = NULL;
	int index = 0;

	if (cmd_str == NULL || pcmd == NULL)
	{
		return -1;
	}

	// 获取命令参数
	p_cmd_name = strtok(cmd_str, " ");
#ifdef DEBUG
	printf("[DEBUG]: cmd_name : %s\n", p_cmd_name);
#endif
	// 复制到命令结构体
	strcpy(pcmd->cmd_name, p_cmd_name);

	// 对剩下的命令参数进行拆分
	for (;;)
	{
		p_cmd_arg = strtok(NULL, " ");
		if (p_cmd_arg == NULL)
		{
			break;
		}

		strcpy(pcmd->cmd_arg_list[index++], p_cmd_arg);
	}
	pcmd->cmd_arg_count = index;

#ifdef DEBUG
	print_command_info(pcmd);

#endif
}

// 分发命令到具体模块
int cmd_dispatch(cmd_t *pcmd)
{
	if (pcmd == NULL)
	{
		return -1;
	}

	if (strcmp(pcmd->cmd_name, "ls") == 0)
	{
		printf("ls mode\n");
		cmd_ls_execute(pcmd);
	}
	else if (strcmp(pcmd->cmd_name, "cp") == 0)
	{
		printf("cp mode\n");
		cmd_cp_execute(pcmd);
	}
}
